package com.other;

/**
 * Created by baiguantao on 2017/11/25.
 */

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.other.generater.Code;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * 远程执行linux的shell script
 *
 * @author Ickes
 * @since V0.1
 */
public class LinuxUtilsTest {
    //字符编码默认是utf-8
    private static String DEFAULTCHART = "UTF-8";
    private Connection conn;
    private Session session;
    private String ip;
    private int port = 22;
    private String userName;
    private String userPwd;

    public LinuxUtilsTest(String ip, String userName, String userPwd) {
        this.ip = ip;
        this.userName = userName;
        this.userPwd = userPwd;
    }

    public LinuxUtilsTest(String ip, String userName, String userPwd, int port) {
        this.ip = ip;
        this.userName = userName;
        this.userPwd = userPwd;
        this.port = port;
    }


    public LinuxUtilsTest() {

    }

    /**
     * 远程登录linux的主机
     *
     * @return 登录成功返回true，否则返回false
     * @author Ickes
     * @since V0.1
     */
    public Boolean login() {
        boolean flg = false;
        try {
            conn = new Connection(ip, port);
            conn.connect();//连接
            flg = conn.authenticateWithPassword(userName, userPwd);//认证
            if (!flg) {
                System.out.println("认证失败");
                conn.close();
                return flg;
            } else {
                System.out.println("认证成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
        return flg;
    }

    public synchronized Session  openSession() {
        try {
            if (session == null) {
                session = conn.openSession();//打开一个会话
            }
            return session;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public synchronized void  closeSession() {
        try {
            if (session != null) {
                session.close();//关闭一个会话
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public synchronized void  closeConnection() {
        try {
            if (conn != null) {
                conn.close();//关闭一个连接
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @since V0.1
     */
    public String execute(String cmd) {
        String result = "";
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param cmd 即将执行的命令
     * @return 命令执行成功后返回的结果值，如果命令执行失败，返回空字符串，不是null
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @since V0.1
     */
    public String executeSuccess(String cmd) {
        String result = "";
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     * @author Ickes
     * @since V0.1
     */
    private String processStdout(InputStream in, String charset) {
        System.out.println("i am in processStdout");
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            if (stdout.available() > 0) {
                while ((line = br.readLine()) != null) {
                    buffer.append(line + "\n");
                }
            } else {
                buffer.append("not str");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                stdout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
    }

    public static void setCharset(String charset) {
        DEFAULTCHART = charset;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
//        LinuxUtilsTest root = new LinuxUtilsTest("10.20.250.248", "baigt", "95q5pada " + Code.main2("PETII43TRNTCXU7T"),18822);
        // bin'an
        LinuxUtilsTest root = new LinuxUtilsTest("10.10.250.249", "baigt", "95q5pada " + Code.main2("UVGYQCGFVGLTKBQ7"),18822);
//        LinuxUtilsTest root = new LinuxUtilsTest("192.168.1.76", "prescription-service", "prescription-service",22);
        Boolean login = root.login();
        if (login) {
            Session session = root.openSession();
//            session.execCommand("ls -lh");
//            InputStream is2 = session.getStdout();
            InputStream is = session.getStdout();
            TimeUnit.MILLISECONDS.sleep(1000);
            String result = root.processStdout(is, DEFAULTCHART);
            System.out.println("执行:"+result);
        }
        root.closeSession();
        root.closeConnection();
    }
}